package com.loooooo.pm2024.utils;


import com.loooooo.pm2024.exception.MyBaseException;
import org.apache.commons.codec.binary.Hex;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.StandardCopyOption;
import java.security.MessageDigest;

public class FileUtils {

    public static void deleteDir(File dir) {

        try {
            org.apache.commons.io.FileUtils.forceDelete(dir);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void copy(File from, File to) {
        System.out.println(String.format("copy1 %s %s", from.getAbsolutePath(), to.getAbsolutePath()));
        try {
            if (!to.getParentFile().exists()) to.getParentFile().mkdirs();

            if (from.isFile()) {
                Files.copy(from.toPath(), to.toPath(), StandardCopyOption.REPLACE_EXISTING);
            } else {
                for (File f : from.listFiles()) {
                    File a = new File(from.getAbsolutePath(), f.getName());
                    File b = new File(to.getAbsolutePath(), f.getName());
                    copy(a, b);
                }
            }

        } catch (IOException e) {
            e.printStackTrace();
            MyBaseException.throwMe(10500, e.getMessage());
        }
    }

    public static String getMD5(File file) {
        FileInputStream fileInputStream = null;
        try {
            MessageDigest MD5 = MessageDigest.getInstance("MD5");
            fileInputStream = new FileInputStream(file);
            byte[] buffer = new byte[8192];
            int length;
            while ((length = fileInputStream.read(buffer)) != -1) {
                MD5.update(buffer, 0, length);
            }
            return new String(Hex.encodeHex(MD5.digest()));
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        } finally {
            try {
                if (fileInputStream != null) {
                    fileInputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }


    public static boolean deleteFile(File file) {

        if (file.isDirectory()) {
            for (File d : file.listFiles()) {
                deleteFile(d);
            }
        }
        return file.delete();
    }


    public static void main(String[] args) {
        //deleteDir(new File("/test/test/test"));
        copy(new File("/temp/cp/a"), new File("/temp/cp/b"));
    }
}
